<?php
namespace app\common\job;

use think\queue\Job;
use app\common\logic\Order as OrderLogic;

/**
 * 同步更新订单消费者
 * @author King
 *
 */
class SyncOrder{

	protected $logName = 'syncOrder';
	protected $clientOrdernum = '';

	public function fire(Job $job, $data){

		if ($job->attempts() > 3) {
			$this->failed($data);
		}
		$this->clientOrdernum = '';
		$this->logName = 'syncOrder';

		try {
			$res = json_decode($data, true);
			$this->clientOrdernum = arrayGet($res, 'produceOrderId', '');
			if (empty($this->clientOrdernum)) throw new \Exception("订单数据解析异常");
			$mes = arrayGet($res, 'mes', '999');
			$history = arrayGet($res, 'history', 0);
			$this->logName .= $mes;
			if ($history) $this->logName .= 'History';

			$clientOrderStatus = arrayGet($res, 'status'); // 客户订单号接单状态
			if ($clientOrderStatus == '待接单') throw new \Exception("订单{$this->clientOrdernum}状态为待接单");

			(new OrderLogic())->sync($res, true);

			$msg = "订单{$this->clientOrdernum}同步更新成功";
			consoleLog($msg);
			addLog($msg, $this->logName);
		} catch (\Exception $e) {
			if ($this->clientOrdernum != '') {
				$key = ORDER_HASH . $this->clientOrdernum;
				cache($key, null);
			}
			consoleLog($e->getMessage());
			addLog($e->getMessage(), $this->logName);
		}

		$job->delete();
	}

	public function failed($data){
		if ($this->clientOrdernum) {
			cache(ORDER_HASH . $this->clientOrdernum);
		}
		$msg = "订单{$this->clientOrdernum}执行多次失败";
		consoleLog($msg);
		addLog($msg, $this->logName);
	}

}